<template>
  <div class="login-container">
    <!-- 顶部 -->
    <div class="absolute-lt flex-x-end p-3 w-full">
      <!-- <el-switch
        v-model="isDark"
        inline-prompt
        active-icon="Moon"
        inactive-icon="Sunny"
        @change="toggleTheme"
      /> -->
      <lang-select class="ml-2 cursor-pointer" />
    </div>
    <!-- 登录表单 -->
    <div class="login-content">
      <div class="left">1</div>
      <div class="right">
        <el-card
          class="!border-none !bg-[#ffffff61] !rounded-1% w-180 <sm:w-85 pl-[5rem] pr-[5rem]"
        >
          <div class="text-center relative">
            <h2 class="text-[32px]">{{ defaultSettings.title }}</h2>
            <el-tag class="ml-2 absolute-rt">{{
              defaultSettings.version
            }}</el-tag>
          </div>

          <el-form
            ref="loginFormRef"
            :model="loginData"
            :rules="loginRules"
            class="login-form"
          >
            <!-- 用户名 -->
            <el-form-item prop="userAccount">
              <div class="flex-y-center w-full">
                <svg-icon icon-class="user" class="mx-2" />
                <el-input
                  ref="userAccount"
                  v-model="loginData.userAccount"
                  placeholder="请输入账号"
                  name="userAccount"
                  size="large"
                  class="h-[48px]"
                />
              </div>
            </el-form-item>

            <!-- 密码 -->
            <el-tooltip
              :visible="isCapslock"
              :content="$t('login.capsLock')"
              placement="right"
            >
              <el-form-item prop="password">
                <div class="flex-y-center w-full">
                  <svg-icon icon-class="lock" class="mx-2" />
                  <el-input
                    v-model="loginData.password"
                    placeholder="请输入密码"
                    type="password"
                    name="password"
                    @keyup="checkCapslock"
                    @keyup.enter="handleLogin"
                    size="large"
                    class="h-[48px] pr-2"
                    show-password
                  />
                </div>
              </el-form-item>
            </el-tooltip>

            <!-- 验证码 -->
            <el-form-item prop="verificationCode">
              <div class="flex-y-center w-full">
                <svg-icon icon-class="captcha" class="mx-2" />
                <el-input
                  v-model="loginData.verificationCode"
                  auto-complete="off"
                  size="large"
                  class="flex-1"
                  placeholder="请输入验证码"
                  @keyup.enter="handleLogin"
                />

                <div class="captcha">
                  <span @click="getCaptcha">{{ captchaBase64 }}</span>
                </div>
              </div>
            </el-form-item>

            <!-- 登录按钮 -->
            <el-button
              :loading="loading"
              type="primary"
              size="large"
              class="w-full mt-[3rem]"
              @click.prevent="handleLogin"
              >{{ $t("login.login") }}
            </el-button>
          </el-form>
        </el-card>
      </div>
    </div>

    <!-- ICP备案 -->
    <div
      class="absolute bottom-1 text-[12px] text-center color-[#666]"
      v-show="icpVisible"
    >
      <p>Copyright © 2016 - 2024 上海贸宝信息技术有限公司</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useSettingsStore, useUserStore } from "@/store";
import AuthAPI from "@/api/auth";
import { LoginData } from "@/api/auth/model";
import type { FormInstance } from "element-plus";
import { LocationQuery, LocationQueryValue, useRoute } from "vue-router";
import router from "@/router";
import defaultSettings from "@/settings";
import { ThemeEnum } from "@/enums/ThemeEnum";
import { sm4 } from "gm-crypt";

// Stores
const userStore = useUserStore();
const settingsStore = useSettingsStore();

// Internationalization
const { t } = useI18n();

// Reactive states
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
const icpVisible = ref(true);
const loading = ref(false); // 按钮loading
const isCapslock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串
const loginFormRef = ref<FormInstance>(); // 登录表单ref
const { height } = useWindowSize();

let key = "AwXOF5IRtHNuQuJX";
let sm4Config = {
  key: key, // 密钥
  mode: "ecb", // 加密的方式有两种，ecb和cbc两种
  cipherType: "base64",
};
let sm4Util = new sm4(sm4Config);
// operat1288
// L20240729
const loginData = ref<LoginData>({
  userAccount: "",
  password: "",
  clientId: "",
  verificationCode: "",
});

const loginRules = computed(() => {
  return {
    userAccount: [
      {
        required: true,
        trigger: "blur",
        message: "请输入账号！",
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: "请输入密码！",
      },
    ],
    verificationCode: [
      {
        required: true,
        trigger: "blur",
        message: "请输入验证码！",
      },
    ],
  };
});

/** 获取验证码 */
function getCaptcha() {
  AuthAPI.getCaptcha().then((data) => {
    const { clientId, verificationCode } = data;
    loginData.value.clientId = clientId;
    captchaBase64.value = verificationCode;
    loginData.value.verificationCode = verificationCode;
  });
}

/** 登录 */
const route = useRoute();
function handleLogin() {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginData.value)
        .then(() => {
          router.push({ path: "/" });
        })
        .catch(() => {
          getCaptcha();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

/** 主题切换 */
const toggleTheme = () => {
  const newTheme =
    settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

/** 根据屏幕宽度切换设备模式 */
watchEffect(() => {
  if (height.value < 600) {
    icpVisible.value = false;
  } else {
    icpVisible.value = true;
  }
});

/** 检查输入大小写 */
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}

// 自动登录
function f_AutoLogin() {
  let paramsUrl = route.query.sm4;
  let autoLoginData = JSON.parse(sm4Util.decrypt(paramsUrl));
  loginData.value.userAccount = autoLoginData.username;
  loginData.value.password = autoLoginData.password;
  handleLogin();
}

onMounted(() => {
  getCaptcha();
  // 是否自动登录
  let paramsUrl = route.query.sm4;
  if (paramsUrl) {
    setTimeout(() => {
      f_AutoLogin();
    }, 200);
  }
});
</script>

<style lang="scss" scoped>
html.dark .login-container {
  background: url("@/assets/images/login-bg-dark.jpg") no-repeat center right;
}

.login-container {
  overflow-y: auto;
  background-color: #e9effd;
  background-size: contain;

  @apply wh-full flex-center;

  .login-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
    width: 100%;

    .left {
      width: 50%;
      height: 800px;
      color: transparent;
      background: red;
      background: url("@/assets/images/login-bg.png") no-repeat center left;
      background-size: auto 800px;
    }

    .right {
      width: 50%;
    }
  }

  .login-form {
    padding: 30px 10px;
  }

  h2 {
    font-family: cursive;
  }
}

.el-form-item {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      /* 通过延时渲染背景色变相去除背景颜色 */
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}

.captcha {
  position: absolute;
  top: 0;
  right: 0;

  span {
    display: inline-block;
    width: 80px;
    height: 38px;
    font-family: fantasy;
    font-size: 24px;
    line-height: 38px;
    color: #32be55;
    text-align: center;
    background: #ccfff382;
  }
}
</style>
